package com.zxd.interview.eightthread.cas;

/**
 * 两个线程进行争夺CAS操作
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.cas
 * @Description : 两个线程进行争夺CAS操作
 * @Create on : 2023/6/4 20:49
 **/
public class TwoThreadsCompetition implements Runnable{

    public static void main(String[] args) throws InterruptedException {
        TwoThreadsCompetition twoThreadsCompetition = new TwoThreadsCompetition();
        twoThreadsCompetition.value = 0;
        Thread t1 = new Thread(twoThreadsCompetition);
        Thread t2 = new Thread(twoThreadsCompetition);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(twoThreadsCompetition.value);

    }


    private volatile int value;

    public synchronized int compareAndSwap(int expectedValue, int newValue){
        int oldValue = value;
        if(oldValue == expectedValue){
            System.out.println("Thread =>" + Thread.currentThread().getName() + " modify Value");
            value = newValue;
        }
        return oldValue;
    }

    @Override
    public void run() {
        compareAndSwap(0, 1);
    }
}
